package com.chris.security.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class LoginUtils {

    public static String getSalt(String username) {
        // 生成盐  并存储到redis中
        String salt = "test_salt";    // BCrypt.gensalt();
        /**
         * @todo 将salt保存到数据库或者缓存中
         * redisTemplate.opsForValue().set("token:"+username, salt, 3600, TimeUnit.SECONDS);
         */
        return salt;
    }

    public static void removeSalt() {
        // 删除redis 中的盐
    }

    public static String getToken(String userId, String username) {
        String salt = getSalt(username);
        Algorithm algorithm = Algorithm.HMAC256(salt);
        Date date = new Date(System.currentTimeMillis() + 3600 * 1000);  //设置1小时后过期
        return JWT.create()
                .withSubject(username)
                .withExpiresAt(date)
                .withIssuedAt(new Date())
                .withClaim("userId", userId)
                .sign(algorithm);
    }

    public static JWTVerifier getTokenVerify(String username) {
        Algorithm algorithm = Algorithm.HMAC256(getSalt(username));
        return JWT.require(algorithm)
                .withSubject(username)
                .build();
    }

    public static String getLoginUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //从session里面获取对应的值
        String token = (String) request.getHeader("Authorization");
        // 解析  获取userId
        if(StringUtils.isNotBlank(token)) {
            DecodedJWT decode = JWT.decode(token);
            String username = decode.getSubject();
            JWTVerifier tokenVerify = getTokenVerify(username);
            DecodedJWT verify = tokenVerify.verify(token);
            return verify.getClaim("userId").asString();
        }
        return null;
    }

}
